package com.yzh.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yzh.common.model.entity.UserInterfaceInfo;
import com.yzh.common.common.ErrorCode;
import com.yzh.common.exception.BusinessException;
import com.yzh.project.mapper.UserInterfaceInfoMapper;
import com.yzh.project.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 10292
 * @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
 * @createDate 2023-06-01 10:24:07
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userInterfaceInfo.getInterfaceInfoId() <= 0 || userInterfaceInfo.getUserId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
        }
        if (userInterfaceInfo.getLeftNum() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余调用次数为0次");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户或接口不存在");
        }
        synchronized (this) {
            //todo 考虑上锁、事务
            UpdateWrapper<UserInterfaceInfo> wrapper = new UpdateWrapper<>();
            wrapper.eq("interfaceInfoId", interfaceInfoId);
            wrapper.eq("userId", userId);
            wrapper.gt("leftNum", 0);
            wrapper.setSql("leftNum = leftNum - 1, totalNum = totalNum + 1");
            return this.update(wrapper);
        }
    }
}




